﻿using System;
using System.IO;
/// <summary>
/// 目录操作相关工具类
/// </summary>
public static class DirectoryTool
{
    /// <summary>
    /// 创建目录文件夹
    /// </summary>
    /// <param name="path">文件夹路径</param>
    public static void CreateDir(string path)
    {
        DirectoryInfo pPath = new DirectoryInfo(path);
        if (!string.IsNullOrEmpty(path) && !pPath.Exists)
        {
            Directory.CreateDirectory(path);
        }
    }
    /// <summary>
    /// 创建文件夹
    /// 创建文件路径,去掉文件名创建前面的路径
    /// </summary>
    /// <param name="filePath">文件路径</param>
    public static string CreateDirWithFilePath(string filePath)
    {
        try
        {
            string[] s = filePath.Split('/');
            if (s.Length > 0)
            {
                filePath = filePath.Replace(s[s.Length - 1], "");
            }
            CreateDir(filePath);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.LogError($"CreateDirWithFilePath error：{ex.Message},{ex.StackTrace}");
            return ex.Message;
        }
        return null;
    }

    //删除文件夹
    public static void SafeDelDir(string dirPath)
    {
        if (!Directory.Exists(dirPath))
        {
            return;
        }
        Directory.Delete(dirPath, true);
    }

    //创建文件夹, 并保存文件
    public static string SaveFile(string path, byte[] buff)
    {
        string createDir = CreateDirWithFilePath(path);
        if (string.IsNullOrEmpty(createDir))
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buff, 0, buff.Length);
                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogError($"SaveFile error：{ex.Message},{ex.StackTrace}");
                return ex.Message;
            }
        }
        else
        {
            return createDir;
        }
        return null;
    }

    public static string SaveFile(string path, string content)
    {
        string createDir = CreateDirWithFilePath(path);
        if (string.IsNullOrEmpty(createDir))
        {
            try
            {
                File.WriteAllText(path, content);
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogError($"SaveFile error：{ex.Message},{ex.StackTrace}");
                return ex.Message;
            }
        }
        else
        {
            return createDir;
        }
        return null;
    }

    //移动文件到指定路径
    public static void FileMoveTo(FileInfo srcFileInfo, string dstFilePath)
    {
        string dirPath = Path.GetDirectoryName(dstFilePath);
        if (!Directory.Exists(dirPath))
            Directory.CreateDirectory(dirPath);
        srcFileInfo.MoveTo(dstFilePath);
    }
}